﻿using System;
using System.IO;
using System.Net;

class TestServer
{
    static void Main()
    {
        var httpPort = new HttpListener();
        // handle every request that has a request Uri starting
        // with "http://" and ending with ":8080/", i.e., anything
        // addressed to port 8080
        httpPort.Prefixes.Add("http://+:8080/");
        httpPort.Start();

        while (true)
        {
            try
            {
                HttpListenerContext context = httpPort.GetContext();
                LogRequest(context.Request);
                HandleRequest(context);
                context.Response.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }

    static void HandleRequest(HttpListenerContext context)
    {
        context.Response.StatusCode = (int)HttpStatusCode.OK;
        // set up an appropriate content if necessary
    }

    static void LogRequest(HttpListenerRequest request)
    {
        Console.BufferWidth = 100;  // allow up to 100 characters per line

        // request line
        Console.WriteLine(request.HttpMethod + " " +
                          request.RawUrl + " " +
                          "HTTP/" + request.ProtocolVersion);

        // request headers
        foreach (String name in request.Headers)
        {
            Console.WriteLine(name + ": " + request.Headers[name]);
        }

        // request body
        Console.WriteLine();
        var buffer = new byte[request.ContentLength64];
        Stream stream = request.InputStream;
        int toRead = buffer.Length;
        while (toRead > 0)
        {
            // already read: buffer.Length - toRead
            int read = stream.Read(buffer, buffer.Length - toRead, toRead);
            toRead = toRead - read;
        }
        Console.WriteLine(request.ContentEncoding.GetString(buffer));
    }
}
